﻿using System;
using System.Globalization;
using System.Windows;
using Microsoft.Phone.Shell;
using Tfs.OnTheRoad.Model;
using System.Windows.Navigation;
namespace Tfs.OnTheRoad.Commands
{
    /// <summary>
    /// Navigates to WorkItems Overview
    /// </summary>

    public class NavigateToWorkItemsOverviewCommand : BaseCommand
    {    
        public override void Execute(object parameter)
        {
            System.Windows.Controls.SelectionChangedEventArgs args = parameter as System.Windows.Controls.SelectionChangedEventArgs;
            if(args!=null && args.AddedItems.Count>0)
            {                
                var summaryItem = args.AddedItems[0] as Tfs.OnTheRoad.ViewModel.WorkItemSummaryItem;
                if (summaryItem != null)
                {
                    if (summaryItem.CurrentLevel == 1)
                        PhoneApplicationService.Current.State["CurrentQuery"] = null;
                    NavigateTo(string.Format("/Pages/WorkItemsOverviewPage.xaml?filter={0}&level={1}", summaryItem.Filter, summaryItem.CurrentLevel+1));
                    return;
                }
                var summaryChildItem = args.AddedItems[0] as Tfs.OnTheRoad.ViewModel.WorkItemSummaryItem.ChildSummaryItem;
                if (summaryChildItem != null)
                {
                    if (summaryChildItem.Parent.CurrentLevel == 1)
                        PhoneApplicationService.Current.State["CurrentQuery"] = null;
                    NavigateTo(string.Format("/Pages/WorkItemsOverviewPage.xaml?filter={0}&level={1}", summaryChildItem.Filter, summaryChildItem.Parent.CurrentLevel + 1));
                    return;
                }

                // Set the selected item as the current item.
                var currentQuery = args.AddedItems[0] as Query;
                if (currentQuery!=null && string.Compare(currentQuery.QueryType, "List", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    MessageBox.Show("Only List Queries are supported.");
                    return;
                }
                else
                    PhoneApplicationService.Current.State["CurrentQuery"] = currentQuery;

                // Navigate to the new page.
                if(currentQuery!=null)
                    //We start the queries with Level 2 to use same settings from the drillDown of the main chart
                    NavigateTo(string.Format(CultureInfo.InvariantCulture, "/Pages/WorkItemsOverviewPage.xaml?queryId={0}&level=2", currentQuery.Id));
            }
        }
    }
}